package com.olap.starter.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SQLExceptionUtil {

    public static void execute(Exception e){
        e.printStackTrace();
        String message = e.getMessage();
        verificationTableNotExist(message);
        verificationFieldNotExist(message);
        throw new RuntimeException(e.getMessage());
    }
    public static void verificationTableNotExist(String message){
        int tableDExist = message.indexOf("nested exception is java.sql.SQLSyntaxErrorException: Table");
        if (tableDExist != -1) {
            String regex = "'([^']+\\\\*[^']+)'";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(message.substring(tableDExist));
            if (matcher.find()) {
                String tableName = matcher.group(1); // 捕获组1包含整个表名（包括数据库名和表名）
                String[] split = tableName.split("\\.");
                if(split.length == 1){
                    throw new RuntimeException("数据库不存在表[" + split[0] + "]，请检查SQL是否正常!");
                }
                throw new RuntimeException("数据库[" + split[0] + "]不存在表[" + split[1] + "]，请检查SQL是否正常!");
            }
        }
    }

    public static void verificationFieldNotExist(String message){
        int tableDExist = message.indexOf("nested exception is java.sql.SQLSyntaxErrorException: Unknown column");
        if (tableDExist != -1) {
            String regex = "'([^']+\\\\*[^']+)'";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(message.substring(tableDExist));
            if (matcher.find()) {
                String tableName = matcher.group(1); // 捕获组1包含整个表名（包括数据库名和表名）
                String[] split = tableName.split("\\.");
                if(split.length == 1){
                    throw new RuntimeException("SQL异常，表中不存在字段[" + split[0] + "]，请检查SQL是否正常!");
                }
                throw new RuntimeException("SQL异常，表["+split[0]+"]不存在字段[" + split[1] + "]，请检查SQL是否正常!");
            }
        }
    }
}
